#!/usr/local/bin/python
# -*- coding: utf-8 -*-

import datetime
from flask import Flask, url_for, request, session, render_template, redirect
from json import dumps

from bompy import app
from utils import q, table, login_required, get2parameters, formtable, textinput, unitoptions, designoptions, typeoptions
from model import Design


@app.route('/design')
@login_required
@get2parameters
def design(edit=None):
    form = (
    ("Design ID",textinput("ID")),
    ("Description",textinput("DS")),
    ("Type",typeoptions("IDT")),
    ("Purchase unit",unitoptions("IDUP")),
    ("Application unit",unitoptions("IDUA"))
    )
    hidden=["""<input type="hidden" name="mode" value="add">"""]
    editing = False
    if edit: #starting to edit
        d = Design.getCurrent(edit)
        form = (
        ("Design ID",textinput("ID",d.ID_Design,readonly=True)),
        ("Description",textinput("DS",d.Description_Std)),
        ("Type",typeoptions("IDT",d.ID_Design_Type)),
        ("Purchase unit",unitoptions("IDUP",d.ID_Unit_Purchase)),
        ("Application unit",unitoptions("IDUA",d.ID_Unit_Application))
        )
        hidden=("""<input type="hidden" name="mode" value="edit">""",)
        editing = True
    f=formtable(form,hidden,"_design_db")
    t=table(["ID","Description","Type","Created","By user","Updated","By user","","","","","","",""])
    return render_template("design.html", editing=editing, f=f, t=t)


@app.route('/_design_search')
def design_search():
    d={"aaData":[]}
    q = Design.query.all()
    for i in q:
        if i.isCurrent():
            d["aaData"].append(i.table())
    return dumps(d)


@app.route('/_design_db')
@get2parameters
def design_db(mode, ID, DS=None, IDT=None, IDUP=None, IDUA=None):
    print IDT
    if mode == "edit": #TODO no va, hay que aniadir uno nuevo, y terminar el anterior
        cursor.execute("""
        select Start_Date,User_Create
        from Design
        where End_Date = 0
        and ID_Design="""+q(ID))
        row = cursor.fetchall()[0]
        SD=row[0]
        UC=row[1]
        cursor.execute("""
        update Design
        set End_Date = now()
        where ID_Design = """ + q(ID)
        )
        cursor.execute("""
        insert into Design
        (ID_Design, Description_Std, ID_Design_Type, ID_Unit_Purchase, 
        ID_Unit_Application, Start_Date, User_Create, Update_Date, User_Update)
        values
        (%s, %s, %s, %s, %s, %s, %s, now(), %s)
        """
        %(q(ID), q(DS), q(IDT), q(IDUP), q(IDUA), q(SD),q(UC), q(Usercode) ))
        db1.commit()
        return redirect(url_for('design'))
    if mode == "add":
        cursor.execute("""
        insert into Design
        (ID_Design, Description_Std, ID_Design_Type, ID_Unit_Purchase,
        ID_Unit_Application, Start_Date, User_Create)
        values
        (%s, %s, %s, %s, %s, now(), %s)
        """
        %(q(ID), q(DS), q(IDT), q(IDUP), q(IDUA), q(Usercode) ))
        db1.commit()
        return redirect(url_for('design'))
    if mode == "delete":
        cursor.execute("""
        update Design
        set End_Date = now()
        where ID_Design = """ + q(ID)
        )
        db1.commit()
        return redirect(url_for('design'))

